/**
 * @description  : uni 平台提供的集合类的api适配
 * @descriptionDetail :
 * @copyright    : 浙江烟草
 * @author       : mc
 * @create       : 2022-09-04 19:33:31
 */

import {
	pathToBase64,
} from 'image-tools'

/**
 * 钉钉提示
 * @param {*} msg     提示信息
 * @param {*} title   标题(可选)
 */
const alert = (msg, title, success) => {
	uni.showModal({
		title: title || '提示',
		content: msg,
		confirmText: "确定",
		success: function(res) {
			if (res.confirm) {
				success && success();
			}
		},
	});
};

/**
 * 钉钉toast弹窗
 */
const toast = (str) => {
	uni.showToast({
		title: str,
	});
};

/**
 * 是否显示顶部的自定义导航栏  并不当做顶部导航栏是否显示，只是用作代码中的配套
 * @returns
 */
const isHideNav = () => {
	return false;
};

/**
 * 获取当前的地理位置、速度
 * @param {Object} type  wgs84返回gps 坐标，gcj02返回国测局坐标
 */
const getLocation = function(type) {
	return new Promise(function(resolve, reject) {
		uni.getLocation({
			type: type,
			success: function(res) {
				resolve(res);
			},
			fail(err) {
				reject(err);
			},
		});
	});
}

/**
 *  打开地图选择位置
 * @param {Object} latitude
 * @param {Object} longitude
 */
const chooseLocation = function(latitude, longitude) {
	return new Promise(function(resolve, reject) {
		uni.chooseLocation({
			success: function(res) {
				resolve(res);
			},
			fail(e) {
				reject(e);
			},
		});
	});
}
/**
 * 使用应用内置地图查看位置
 * @param {Object} latitude
 * @param {Object} longitude
 */
const openLocation = function(latitude, longitude) {
	return new Promise(function(resolve, reject) {
		uni.openLocation({
			latitude: Float(latitude),
			longitude: Float(longitude),
			success: function() {
				resolve(true);
			},
			fail() {
				reject(false);
			},
		});
	});
}

/**
 * 客户端(apk/ipa)的版本名称
 */
const getAppVersion = function() {}

/**
 * 客户端的版本号
 */
const getAppVersionCode = function() {}
/**
 * 从本地相册选择图片或使用相机拍照
 * @param {Object} maxSize 最多可以选择的图片张数，默认   1
 */
const chooseImage = function(maxSize) {
	return new Promise(function(resolve, reject) {
		uni.chooseImage({
			count: maxSize ? maxSize : 1, // 默认1
			sizeType: ['original', 'compressed', ], // 可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album', 'camera', ], // 从相册选择或者拍照
			success: function(res) {
				resolve(res.tempFilePaths);
			},
			fail(e) {
				reject(e);
			},
		});
	});
}

/**
 * 从本地相册选择图片或使用相机拍照 获取base64
 * @param {Object} maxSize 最多可以选择的图片张数，默认   1
 */
const chooseImageToBase64 = function(maxSize) {
	return new Promise(function(resolve, reject) {
		uni.chooseImage({
			count: maxSize ? maxSize : 1, // 默认1
			sizeType: ['original', 'compressed', ], // 可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album', 'camera', ], // 从相册选择或者拍照
			success: function(res) {
				Promise.all(res.tempFilePaths.map(itm => pathToBase64(itm))).then((dta) => {
					resolve(dta);
				}).catch(err => {
					reject(err);
				});
			},
			fail(e) {
				reject(e);
			},
		});
	});
}

/**
 * 从本地相册选择图片或使用相机拍照
 * @param {Object} maxSize 最多可以选择的图片张数，默认   1
 * @param {Int} sType 0 默认，1 相册 ， 2 拍照
 * @param {Number} quality   0-1
 * @param {Number} widthScale 0-1
 * @param {Boolean} backType 0 string   1 obj {path: "", url: ""}
 */
const chooseImageToCompress = function({
	maxSize = 1,
	sType = 0,
	quality = 0.65,
	widthScale = 0.7,
	backType = 0,
}) {
	return new Promise((resolve, reject) => {
		let ar = ['album', 'camera', ];
		if (sType == 1) {
			ar = ['album', ];
		} else if (sType == 2) {
			ar = ['camera', ];
		}
		uni.chooseImage({
			count: maxSize,
			sizeType: ['original', 'compressed', ],
			sourceType: ar,
			success: res1 => {
				uni.showLoading({
					title: '正在压缩...',
				});
				Promise.all(res1.tempFilePaths.map(itm => pathToBase64(itm))).then((dta) => {
					console.log('dtadta', dta[0])
					compressBase64Image(dta[0], 800, 600, 0.4).then(compressedBase64 => {
						resolve([compressedBase64])
						uni.hideLoading();
						console.log(compressedBase64, 'compressedBase64'); // 输出压缩后的Base64字符串
					}).catch(error => {
						console.error(error);
					});
					// resolve(dta);
				}).catch(err => {
					reject(err);
				});
			},
			fail: err => {
				reject();
			},
		});
	});
}
/**
 * 图片压缩
 */
const compressImage = function(file, fileExtra, num, quality = 0.3, widthScale = 0.8, backType = 0) {
	let name = "_doc/tmpImg/" + Date.now() + "_tmp." + fileExtra; // _doc/upload/F_ZDDZZ-1467602809090.jpg
	return new Promise((resolve, reject) => {
		// #ifdef APP-PLUS
		plus.zip.compressImage({
			src: file, // src: (String 类型 )压缩转换原始图片的路径
			dst: name, // 压缩转换目标图片的路径
			quality: quality * 100, // quality: (Number 类型 )压缩图片的质量.取值范围为1-100
			overwrite: true, // overwrite: (Boolean 类型 )覆盖生成新文件
			width: (widthScale * 100) + "%",
			height: "auto",
		}, function(event) {
			if (backType == 0) {
				resolve(pathToBase64(name));
			} else {
				pathToBase64(name).then(pp => {
					resolve({
						path: name,
						url: pp,
					});
				});
			}
		}, function(err) {
			plus.nativeUI.toast("压缩图片失败，请稍候再试");
			reject();
		});
		// #endif
		// #ifndef APP-PLUS
		let img = new Image();
		img.src = file;
		img.onload = function() {
			let newBase64 = ImageScale.compressImage(img, {
				// 压缩质量
				quality: quality,
				mime: 'image/jpeg',
				// 压缩时的放大系数，默认为1，如果增大，代表图像的尺寸会变大(最大不会超过原图)
				compressScaleRatio: 1,
				// ios的iPhone下主动放大一定系数以解决分辨率过小的模糊问题
				iphoneFixedRatio: 1.5,
				// 是否采用原图像素（不会改变大小）
				isUseOriginSize: false,
				// 增加最大宽度，增加后最大不会超过这个宽度
				maxWidth: 0,
				// 使用强制的宽度，如果使用，其它宽高比系数都会失效，默认整图使用这个宽度
				forceWidth: img.width * widthScale,
				// 同上，但是一般不建议设置，因为很可能会改变宽高比导致拉升，特殊场景下使用
				forceHeight: 0,
			});
			resolve(newBase64);
		}
		// #endif
	});
}

/**
 * 预览图片
 * @param {Object} urls 需要预览的图片链接列表
 */
const previewImage = function(urls, current) {
	return new Promise(function(resolve, reject) {
		uni.previewImage({
			urls: urls, // 图片集合
			current: current, // 当前图片链接
			success: function(data) {
				resolve(true);
			},
			fail: function(err) {
				reject(false);
			},
		})
	});
}
/**
 * 获取网络类型
 * wifi	wifi 网络
 * 2g	2g 网络
 * 3g	3g 网络
 * 4g	4g 网络
 * ethernet	有线网络	App
 * unknown	Android 下不常见的网络类型
 * none	无网络
 * @param {Object} success
 * @param {Object} fail
 */
const getNetworkType = function() {
	return new Promise(function(resolve, reject) {
		uni.getNetworkType({
			success: function(res) {
				resolve(res.networkType);
			},
			fail(e) {
				reject(e)
			},
		})
	});
}

/**
 * 拨打电话
 * @param {Object} phoneNumber
 */
const makePhoneCall = function(phoneNumber) {
	return new Promise(function(resolve, reject) {
		uni.makePhoneCall({
			phoneNumber: phoneNumber,
			success: () => {
				resolve(true);
			},
			fail() {
				reject(false);
			},
		});
	});
}

/**
 * 发送短信
 * @param {Object} telTo 电话号码 ['18611497504', '15811140520']
 * @param {Object} msgBody 发送内容
 * @param {Object} success
 * @param {Object} fail
 */
const sendMessage = function(telTo, msgBody, success, fail) {
	return new Promise(function(resolve, reject) {
		let msg = plus.messaging.createMessage(plus.messaging.TYPE_SMS);
		msg.to = telTo;
		msg.body = msgBody;
		plus.messaging.sendMessage(msg, (res) => {
			resolve(true);
		}, (e) => {
			reject(false);
		});
	});
}

/**
 * 调起条码扫描
 */
const scan = function() {
	return new Promise(function(resolve, reject) {
		uni.scanCode({
			scanType: ['barCode', 'qrCode', ],
			success: function(res) {
				let barcode = res.result;
				if (barcode.indexOf("许可证号") >= 0) {
					let start = barcode.indexOf("许可证号") + 5;
					console.log('获取的二维码 start：' + start);
					barcode = barcode.substring(start, start + 12);
					barcode = barcode.replace(/(^\s*)|(\s*$)/g, "");
					console.log('获取的二维码 licCode：' + barcode);
				}
				resolve(barcode);
			},
			fail(e) {
				reject(e);
			},
		});
	});
}
/**
 *  提示框
 * @param String title 标题
 * @param String content 提示类容
 * @param String confirmText 确定按钮文字
 * @param Boolean showCancel 是否显示取消按钮
 * @param String cancelText 取消按钮文字
 * @param {Object} success
 * @param {Object} fail
 */
const showModal = function(title, content, confirmText, showCancel, cancelText, success, cancel) {
	uni.showModal({
		title: title,
		content: content,
		confirmText: confirmText,
		showCancel: showCancel,
		cancelText: cancelText,
		success: function(res) {
			if (res.confirm) {
				success();
			} else if (res.cancel) {
				cancel();
			}
		},
	})
}

/**
 * 显示操作菜单
 * @param {Object} title 标题 不需要传：""
 * @param {Object} actionbuttons 操作菜单 [{title:"不同意",style:"destructive"},{title:"1"},{title:"2"},{title:"3"}]
 * @param {Object} cancelText 取消按钮文字
 * @param {Object} success 成功回调
 */
const showActionSheet = function(title, actionbuttons, cancelText, success) {
	// #ifdef APP-PLUS
	let actionstyle = {
		title: title,
		cancel: cancelText,
		buttons: actionbuttons,
	};
	plus.nativeUI.actionSheet(actionstyle, function(e) {
		success(e.index - 1);
	});
	// #endif

	// #ifndef APP-PLUS
	let itemList = [];
	for (let i = 0; i < actionbuttons.length; i++) {
		itemList.push(actionbuttons[i].title);
	}
	uni.showActionSheet({
		title: title,
		itemList: itemList,
		cancelText: cancelText,
		success: (e) => {
			console.log(e.tapIndex)
			success(e.tapIndex);
		},
	})
	// #endif
}

/**
 * 获取系统信息
 */
const getSystemInfo = function() {
	return new Promise(function(resolve, reject) {
		uni.getSystemInfo({
			success: function(res) {
				let data = {
					"brand": res.brand,
					"model": res.model,
					"pixelRatio": res.pixelRatio,
					"screenWidth": res.screenWidth,
					"screenHeight": res.screenHeight,
					"system": res.system,
					"platform": res.platform,
				};
				resolve(data);
			},
			fail(e) {
				reject(e);
			},
		});
	});
}

/**
 *  调起高德 ，百度地图服务
 * @param {string} route 服务类型 t = 0（驾车）= 1（公交）= 2（步行）= 3（骑行）= 4（火车）= 5（长途客车）
 * @param {string} dlat 终点纬度
 * @param {string} dlon 终点经度
 * @param {string} slat 起点纬度
 * @param {string} slon 起点经度
 */
const startNavigation = function(route, dlat, dlon, slat, slon) {
	return new Promise((resolve, reject) => {
		showActionSheet("选择", [{
			title: "高德地图",
		}, {
			title: "百度地图",
		}, ], "取消", function(res) {
			let type1 = "";
			console.log('====' + res);
			if (res === 0) {
				type1 = "amap";
			} else if (res === 1) {
				type1 = "baidu";
			}
			startNav(type1);
		});
		// @param {string} type amap- 高德，baidu-百度
		let startNav = function(type) {
			let success = function(result) {
				resolve(result);
			};
			let fail = function(error) {
				reject(error);
			};
			// 判断平台
			if (uni.getSystemInfoSync().platform == 'android') {
				// 判断是否是 高德 或者 百度
				if (type == "amap") {
					let uri = '';
					if (slat != undefined && slon != undefined) {
						uri = "amapuri://route/plan/?sourceApplication=信用监管&slat=" + slat + "&slon=" + slon + "&dlat=" +
							dlat + "&dlon=" + dlon + "&dev=0&t=" + route;
					} else {
						uri = "amapuri://route/plan/?sourceApplication=信用监管&dlat=" + dlat + "&dlon=" + dlon + "&dev=0&t=" +
							route;
					}
					plus.runtime.openURL(encodeURI(uri), function(e) {
						let err = "";
						try {
							err = e.indexOf("No Activity found") > -1 ? "未安装高德地图" : e;
						} catch (ep) {
							err = e;
						}
						reject(err);
					});
				} else if (type == "baidu") {
					let uri = "";
					if (slat != undefined && slon != undefined) {
						uri = 'baidumap://map/direction?origin=' + slat +
							',' + slon + '&destination=' + dlat +
							',' + dlon + '&coord_type=gcj02&mode=' + BAIDU_NAV[route] + '&src=com.csbi.monopoly.mobile';
					} else {
						uri = 'baidumap://map/direction?destination=' + dlat +
							',' + dlon + '&coord_type=gcj02&mode=' + BAIDU_NAV[route] + '&src=com.csbi.monopoly.mobile';
					}
					plus.runtime.openURL(encodeURI(uri), function(e) {
						let err = "";
						try {
							err = e.indexOf("No Activity found") > -1 ? "未安装百度地图" : e;
						} catch (ep) {
							err = e;
						}
						reject(err);
					});
				}
			} else if (uni.getSystemInfoSync().platform == 'ios') {
				// 判断是否是 高德 或者 百度
				if (type == "amap") {
					let uri = '';
					if (slat != undefined && slon != undefined) {
						uri = "iosamap://path/?sourceApplication=信用监管&slat=" + slat + "&slon=" + slon + "&dlat=" + dlat +
							"&dlon=" + dlon + "&dev=0&t=" + route;
					} else {
						uri = "iosamap://path/?sourceApplication=信用监管&dlat=" + dlat + "&dlon=" + dlon + "&dev=0&t=" + route;
					}
					plus.runtime.openURL(encodeURI(uri), function(e) {
						reject(e);
					});
				} else if (type == "baidu") {
					let uri = 'baidumap://map/navi?location=' + dlat + ',' + dlon + '&coord_type=gcj02&mode=' + BAIDU_NAV[
						route] + '&type=BLK&src=com.csbi.monopoly.mobile';
					plus.runtime.openURL(encodeURI(uri), function(e) {
						reject(e);
					});
				}
			}
		};
	});
}

const closeWindow = function() {
	window.open("about:blank", "_self")
	window.close();
}


const compressBase64Image = function(base64, maxWidth, maxHeight, outputFormat = 'image/jpeg', quality = 0.7) {
	return new Promise((resolve, reject) => {
		const img = new Image();
		img.onload = () => {
			let canvas = document.createElement('canvas');
			let ctx = canvas.getContext('2d');
			let width = img.width;
			let height = img.height;

			if (width > maxWidth) {
				height *= maxWidth / width;
				width = maxWidth;
			}

			if (height > maxHeight) {
				width *= maxHeight / height;
				height = maxHeight;
			}

			canvas.width = width;
			canvas.height = height;
			ctx.drawImage(img, 0, 0, width, height);
			const newDataUrl = canvas.toDataURL(outputFormat, quality);
			resolve(newDataUrl);
		};
		img.onerror = reject;
		img.src = base64;
	});
}

export default {
	getLocation,
	chooseLocation,
	openLocation,
	getAppVersion,
	getAppVersionCode,
	chooseImage,
	previewImage,
	getNetworkType,
	makePhoneCall,
	sendMessage,
	scan,
	showModal,
	showActionSheet,
	getSystemInfo,
	startNavigation,
	chooseImageToBase64,
	chooseImageToCompress,
	isHideNav,
	alert,
	toast,
	closeWindow,
}
